import { modelList, createProgressModel, updateProgressModel } from '@/api/model'
import { fetchList, fetchPv, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

// 模型类型
const modelTypeOptions = [
  { key: 1, displayName: 'BPMN2.0' },
  { key: 2, displayName: 'CMMN' },
  { key: 3, displayName: 'DMN' }
]
// 创建模型方式
const createTypeOptions = [
  { key: 1, displayName: '在线创建' },
  { key: 2, displayName: '本地上传' }
]
// 模型类型显示内容
const modelTypeKeyValue = modelTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
// 创建模型方式显示内容
const crateTypeKeyValue = createTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ModelList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter (status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    modelTypeFilter (modelType) {
      return modelTypeKeyValue[modelType]
    }
  },
  data () {
    return {
      dialogWidth: '700px',
      tableKey: 0,
      modelList: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        modelType: 0,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      modelTypeOptions,
      createTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      progressModelData: {
        modelId: undefined,
        modelName: '',
        modelType: 1,
        createType: 1,
        modelKey: '',
        xmlData: '',
        fileUrl: '',
        remark: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑流程模型',
        create: '创建流程模型'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        modelName: [{ required: true, message: '请输入模型名称, 允许使用中文命名', trigger: 'blur' }],
        modelKey: [{ required: true, message: '请使用英文字母设置模型唯一标志', trigger: 'blur' }],
        modelType: [{ required: true, message: '请选择模型类型', trigger: 'change' }],
        createType: [{ required: true, message: '请选择创建方式', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created () {
    this.getModelList()
  },
  methods: {
    createModel (modelType) {
      let modelName = 'myBpmnModeler'
      if (modelType == 'bpmn') {
        modelName = 'myBpmnModeler'
      } else if (modelType == 'cmmn') {
        modelName = 'myCmmnModeler'
      } else if (modelType == 'dmn') {
        modelName = 'myDmnModeler'
      }
      const { href } = this.$router.resolve({
        name: modelName
      })
      window.open(href, '_blank')
    },
    showModel (modelType) {
      let modelName = 'myBpmnViewer'
      if (modelType == 'bpmn') {
        modelName = 'myBpmnViewer'
      } else if (modelType == 'cmmn') {
        modelName = 'myCmmnViewer'
      } else if (modelType == 'dmn') {
        modelName = 'myDmnViewer'
      }
      const { href } = this.$router.resolve({
        name: modelName
      })
      window.open(href, '_blank')
    },
    getModelList () {
      this.listLoading = true
      modelList(this.listQuery).then(response => {
        this.modelList = response.data.items
        this.total = response.data.total

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter () {
      this.listQuery.page = 1
      this.getModelList()
    },
    handleModifyStatus (row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange (data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID (order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetProgressModelData () {
      this.progressModelData = {
        modelId: undefined,
        modelName: '',
        modelKey: '',
        modelType: 1,
        createType: 1,
        xmlData: '',
        fileUrl: '',
        remark: ''
      }
    },
    handleCreate () {
      this.resetProgressModelData()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.progressModelData.author = 'vue-element-admin'
          createProgressModel(this.progressModelData).then(response => {
            this.modelList.unshift(this.progressModelData)
            // 创建成功，关闭弹框
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            // 打开模型编辑器
            if (this.progressModelData.createType == 1) {
              let modelName = 'BpmnModeler'
              if (this.progressModelData.modelType == 1) {
                modelName = 'BpmnModeler'
              } else if (this.progressModelData.modelType == 2) {
                modelName = 'CmmnModeler'
              } else if (this.progressModelData.modelType == 3) {
                modelName = 'DmnModeler'
              }
              const returnModelId = response.data.modelId
              const { href } = this.$router.resolve({
                name: modelName,
                query: {
                  modelId: returnModelId
                }
              })
              window.open(href, '_blank')
            }
          })
        }
      })
    },
    handleUpdate (row) {
      this.progressModelData = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const thisProgressModelData = Object.assign({}, this.progressModelData)
          updateProgressModel(thisProgressModelData).then(() => {
            // 刷新模型列表数据
            for (const v of this.modelList) {
              if (v.id === this.progressModelData.id) {
                const index = this.modelList.indexOf(v)
                this.modelList.splice(index, 1, this.progressModelData)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            // 打开模型编辑器
            if (this.progressModelData.createType == 1) {
              let modelName = 'BpmnModeler'
              if (this.progressModelData.modelType == 1) {
                modelName = 'BpmnModeler'
              } else if (this.progressModelData.modelType == 2) {
                modelName = 'CmmnModeler'
              } else if (this.progressModelData.modelType == 3) {
                modelName = 'DmnModeler'
              }
              const { href } = this.$router.resolve({
                name: modelName,
                query: {
                  modelId: this.progressModelData.modelId
                }
              })
              window.open(href, '_blank')
            }
          })
        }
      })
    },
    handleDelete (row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.modelList.indexOf(row)
      this.modelList.splice(index, 1)
    },
    handleFetchPv (pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload () {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.modelList)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
